package examples;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServerDemo01 {
    public static void main(String[] args) {
        try {
            // 1.创建socket，并监听端口
            ServerSocket serverSocket = new ServerSocket(6666);

            // 2.获取客户端socket
            Socket socket = serverSocket.accept();

            // 3.准备流资源
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 接受客户端发送的数据
            PrintWriter printWriter = new PrintWriter(new FileWriter("E:\\1023.txt"), true);
            PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);

            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
            long time = dataInputStream.readLong();

            // 4.接收数据，并保存到文件中
            String line = null;
            while ((line = in.readLine()) != null) {
                if (line.equalsIgnoreCase(time + "")) {
                    break;
                }
                printWriter.println(line);
            }

            // 5.
            out.println("文件上传成功！");

            // 6.关闭资源
            printWriter.close();
            serverSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
